package com.quanroon.ysq.master_worker;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;

/**
 * @author quanroong.ysq
 * @version 1.0.0
 * @description
 * @createtime 2021/10/20 21:48
 */
public class Master {
    //任务队列
    protected Queue<Object> workerQueue = new ConcurrentLinkedDeque<>();

    //worker进程队列
    protected Map<String, Thread> threadMap = new HashMap<>();

    //子任务处理结果集
    protected Map<String, Object> resultMap = new ConcurrentHashMap<>();

    /**
    * @description 是否所有的子任务都结束了
    * @author quanroong.ysq
    * @createtime 2021/10/20 22:00
    * @version 1.0.0
    */
    public boolean isComplete(){
        for (Map.Entry<String, Thread> entry : threadMap.entrySet()) {
            if(entry.getValue().getState() != Thread.State.TERMINATED)
                return false;
        }
        return true;
    }

    /**
    * @description master的构造，需要一个worker进程逻辑，和需要的worker进程数量
    * @author quanroong.ysq
    * @createtime 2021/10/20 22:03
    * @version 1.0.0
    */
    public Master(Worker worker, int countWorker) {
        worker.setWorkQueue(workerQueue);
        worker.setResultMap(resultMap);

        for (int i = 0; i < countWorker; i++) {
            threadMap.put(Integer.toString(i), new Thread(worker, Integer.toString(i)));
        }
    }

    /**
    * @description 提交一个任务
    * @author quanroong.ysq
    * @createtime 2021/10/20 22:04
    * @version 1.0.0
    */
    public void submit(Object job){
        workerQueue.add(job);
    }

    /**
    * @description 返回子任务结果集
    * @author quanroong.ysq
    * @createtime 2021/10/20 22:06
    * @version 1.0.0
    */
    public Map<String, Object> getResultMap(){
        return resultMap;
    }

    /**
    * @description 开始运行所有的worker进程，进行处理
    * @author quanroong.ysq
    * @createtime 2021/10/20 22:05
    * @version 1.0.0
    */
    public void execute(){
        for (Map.Entry<String, Thread> entry : threadMap.entrySet()) {
            entry.getValue().start();
        }
    }
}
